//
//  AYMNetworkTool.m
//  QuickCure
//
//   Mr.LV
//

#import "AYMNetworkTool.h"

@protocol NetworkToolsProxy <NSObject>

@optional
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
                                       URLString:(NSString *)URLString
                                      parameters:(id)parameters
                                  uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
                                downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
                                         success:(void (^)(NSURLSessionDataTask *, id))success
                                         failure:(void (^)(NSURLSessionDataTask *, NSError *))failure;

@end



@interface AYMNetworkTool()<NetworkToolsProxy>

@end

@implementation AYMNetworkTool

+(instancetype)sharedManager{

    static AYMNetworkTool *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        instance = [[self alloc]initWithSessionConfiguration:config];
        
        //返回类型
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
        
        //请求格式  非常重要。 没有请求的code为1
        instance.requestSerializer = [AFJSONRequestSerializer serializer];
        
        //5.超时
        instance.requestSerializer.timeoutInterval = 10.0;
    });
    return instance;
}

- (void)request:(RequestMethod)method urlString:(NSString *)urlString parameters:(id)parameters finished:(void (^)(id, NSError *))finished{
    
    NSString *reqMethod = (method == RequestMethodGet) ? @"get" : @"post";
    [[self dataTaskWithHTTPMethod:reqMethod URLString:urlString parameters:parameters uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask *dataTask, id responseObject) {
        
        // 请求成功的回调
        finished(responseObject, nil);
    } failure:^(NSURLSessionDataTask *dataTask, NSError *error) {
        // 请求失败
        finished(nil, error);
    }] resume];
}
//第三方框架检查网络连接
-(BOOL)isReachableByAFN{
    Reachability *reachability = [Reachability reachabilityWithHostName:@"http://iosapi.itcast.cn"];
    //如果能成功连接则会是ture
    return reachability.isReachable;
}

@end
